package com.taotao.job.executor.rpc;

import com.google.common.base.Preconditions;
import com.taotao.job.core.executor.ExecutorContext;
import com.taotao.job.core.rpc.ExecutorIface;
import com.taotao.job.core.trigger.TriggerResult;
import com.taotao.job.core.util.JobBussinessUtil;
import com.taotao.job.executor.bootstrap.TaotaoJobExecutor;
import com.taotao.job.executor.core.JobThread;

import java.util.HashMap;

/**
 * @author fanbeibei
 * @date 2021/4/7 10:54
 */
public class ExecutorIfaceImple implements ExecutorIface {
    @Override
    public TriggerResult triggerRun(ExecutorContext executorContext) {
        JobBussinessUtil.validExecutorContext(executorContext);
        try {
            TaotaoJobExecutor.runJob(executorContext);
        } catch (Exception e) {
            return new TriggerResult(TriggerResult.RESULT_FAIL, executorContext.getJobInstanceId(), e.getMessage());
        }
        return new TriggerResult(TriggerResult.RESULT_SUCCESS, executorContext.getJobInstanceId(), null);
    }

    @Override
    public String getRunRate(Long runInstanceId) {
        Preconditions.checkArgument(null != runInstanceId, "runInstanceId is null");

        return TaotaoJobExecutor.getRunRate(runInstanceId);
    }

    @Override
    public HashMap<Long, String> getAllRunRate() {
        return TaotaoJobExecutor.getAllRunRate();
    }

    @Override
    public int getInstanceInQueueCount(Long jobId) {
        Preconditions.checkArgument(null != jobId, "jobId is null");
        JobThread jobThread = TaotaoJobExecutor.getJobThread(jobId);
        if (null == jobThread) {
            return 0;
        }

        return jobThread.getInstanceInQueueCount();
    }
}
